package fr.insalyon.sims.broadcast.tools;

import java.util.StringTokenizer;

public class InetTools {
	// ------------------------------------------------------- CONSTANTS -- //
	// ------------------------------------------------------ ATTRIBUTES -- //
	// ---------------------------------------------------- CONSTRUCTORS -- //
	// --------------------------------------------------------- METHODS -- //
	
	public static String ipToString(byte[] ip) {
		String result = "";
		
		for (int i = 0; i < ip.length; i++)
			result += (i == 0 ? "" : ".") + (ip[i] + 256) % 256;
		
		return result;
	}
	
	/**
	 * 
	 * @param ip
	 * @return IP address value, or null if IP address string has an invalid
	 * format.
	 */
	public static byte[] stringToIp(String ip) {
		StringTokenizer tokenizer = new StringTokenizer(ip, ".");
		byte[] result = new byte[4];
		
		for (int i = 0; i < 4; i++) {
			if (!tokenizer.hasMoreTokens())
				return null;
			
			int value;
			
			try {
				value = Integer.parseInt(tokenizer.nextToken());
			} catch (NumberFormatException ex) {
				return null;
			}
			
			if (value < 0 || value > 255)
				return null;
			
			result[i] = (byte) value;
		}
		
		return result;
	}
	
	/**
	 * 
	 * @param port
	 * @return Port value, or -1 if port value is invalid.
	 */
	public static int stringToPort(String port) {
		int result = 0;
		try {
			result = Integer.parseInt(port);
		} catch (NumberFormatException ex) {
			return -1;
		}
		
		if (result < 0 || result > 65535)
			return -1;

		return result;
	}
	
	// ------------------------------------------------- PRIVATE METHODS -- //
	// --------------------------------------------------- INNER CLASSES -- //
}
